<?php

/**
 * 微信接口框架SDK
 * Class WxSDK
 */
class WxSDK
{
    // 服务端接口地址，与服务端的 WxConfig::BASEURL 相同。必须以/结尾
    const URL = 'http://hzos.weclouds.cn/api/wechat/wxapi/';
    // 与服务端接口通讯密钥，与服务端的 WxConfig::KEY 相同
    const KEY = 'a0c88b5476a051cef08bc15abe029fdf';//
    // 公众号配置
    const APPID = '';


    /**
     * CURL GET
     * @param string $url
     * @return string
     */
    protected static function curlGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    /**
     * api获取结果
     * @param string $action
     * @return bool|string
     * @throws Exception
     */
    protected static function apiGet($action)
    {
        $data = array(
            'get' => $action,
            'ts'  => time(),
        );
        $data['sign'] = md5(strtolower($data['get'] . self::KEY . $data['ts']));
        $url = self::URL . 'api.php?' . http_build_query($data);
        $data = self::curlGet($url);
        $data = json_decode($data, TRUE);

        if ( !isset($data['errorCode']) || !isset($data['errorMsg']) || !isset($data['result'])){
            throw new Exception('微信接口返回数据异常！', 1);
            return FALSE;
        }
        if ($data['errorCode'] != 0){
            throw new Exception($data['errorMsg'], $data['errorCode']);
            return FALSE;
        }

        return $data['result'];
    }

    /**
     * 获取AccessToken
     * @return string
     */
    public static function getAccessToken()
    {
        return self::apiGet('access_token');
    }

    /**
     * 获取JsApi票据
     * @return string
     */
    public static function getJsApiTicket()
    {
        return self::apiGet('api_ticket');
    }

    /**
     * 获取微信卡券票据
     * @return bool|string
     */
    public static function getCardTicket()
    {
        return self::apiGet('card_ticket');
    }

    /**
     * 获取微信用户信息
     * @param string $callback_url 回调url地址，需要经过一次跳转
     * @param bool   $userinfo     是否获取用户信息。默认为真，为false时仅获取openid
     * @return array 字段：openid、nickname、sex、province、city、country、headimgurl
     */
    public static function getUserInfo($callback_url, $userinfo = TRUE)
    {
        if (isset($_GET['openid'])){
            require_once 'WxAes.php';
            WxAes::$_key = self::KEY;
            $arr_todecrypt = array_slice($_GET,-7);//排除掉callback_url中原来带的参数
            foreach ($arr_todecrypt as $k => $v){
                $arr_todecrypt[$k] = WxAes::decrypt($v);
            }
            return $arr_todecrypt;
        } else {
            $url = self::URL . 'auth.php?';
            if ($userinfo) $url .= 'userinfo=1&';
            $url .= 'callback_url=' . urlencode($callback_url);
            header('Location:' . $url);
            exit;
        }
    }

    /**
     * 生成随机字符串
     * @param int $length 默认为16位
     * @return string
     */
    public static function createNonceStr($length = 16)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++){
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 获取微信转发签名包
     * @return array
     */
    public static function getSignPackage()
    {
        $jsapiTicket = self::getJsApiTicket();
        $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = self::createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => self::APPID,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string,
        );
        return $signPackage;
    }

    /**
     * 是否来自微信浏览器
     * @return bool|int
     */
    public static function is_broswer(){
        if ( !isset($_SERVER['HTTP_USER_AGENT'])) return FALSE;
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') === FALSE){
            return FALSE;
        } else {
            return TRUE;
        }
    }
}